﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using MySql.Data.MySqlClient;

namespace TKWeb.Passport
{
	public partial class Login : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (Global.UserId > 0)
			{
				Response.Redirect("/Portal/JobConfig.aspx");
			}
		}

		protected void Button1_Click(object sender, EventArgs e)
		{
			tbEmail.Text = tbEmail.Text.Trim();
			tbPwd.Text = tbPwd.Text.Trim();

			if (string.IsNullOrEmpty(tbPwd.Text) || string.IsNullOrEmpty(tbEmail.Text))
			{
				lbError.Visible = true;
				lbError.Text = "请输入Email或密码！";
				return;
			}

			if(CheckUser(tbEmail.Text, tbPwd.Text))
			{
				Response.Redirect("/Portal/JobConfig.aspx");
			}
			else
			{
				lbError.Visible = true;
				lbError.Text = "登录失败，Email或密码错误！";
			}
		}

		private bool CheckUser(string email, string pwd)
		{
			System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
			string md5Pwd =  FormsAuthentication.HashPasswordForStoringInConfigFile(string.Format("abc{0}abc", pwd), "MD5");
			object objUserId = Global.DBAccess.ExecuteScalar("select uid from user_info where email=@email and pwd=@pwd", new MySqlParameter("email", email), new MySqlParameter("pwd", md5Pwd));
			if (objUserId == DBNull.Value || objUserId == null)
			{
				return false;
			}

			Global.DBAccess.ExecuteNonQuery("update user_info set logined=sysdate() where uid=@uid", new MySqlParameter("uid", objUserId));
			this.Session["UserId"] = objUserId;
			return true;
		}
	}
}